//入口函数
function loadJsCss(bangbeng) {
    whir.res.pageVersion = bangbeng; //页面版本，用于检测是否需要更新缓存
    whir.res.loadCss("base", "../css/base.css", null);
    whir.res.loadCss("commoncss", "../css/common.css", null);
    whir.res.loadCss("popupcss", "../css/popup.css", null);
    whir.res.loadCss("swipercss", "../css/swiper.min.css", null);
    whir.res.loadJs("loadjs", "../js/load.js", null);
    whir.res.loadJs("zepto", "../js/zepto.js", null);
    whir.res.loadJs("dsbridge", "../js/dsbridge.js", null);
    whir.res.loadJs("templatejs", "../js/template.js", null);
    whir.res.loadJs("commonjs", "../js/common.js", null);
    whir.res.loadJs("zepto", "../js/zepto.js",
        function() {
            whir.res.loadJs("flexible", "../js/flexible.min.js", null);
            whir.res.loadJs("popupjs", "../js/popup.js", null);
            whir.res.loadJs("swiperjs", "../js/swiper.min.js", null);
            whir.res.loadJs("exif", "../js/exif.js", null);
            whir.res.loadJs("zepto.picLazyLoad", "../js/zepto.picLazyLoad.min.js", null);
        });
}

//测试的token、roomId
function getRequests() {
    var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNzM2MzI4NTIiLCJiYXRjaCI6Ii0xIiwiZXhwIjoxNTYzNTA1ODUxfQ.c_y222ASCK0hD8MeMIUt7sgmI5a2XrC4T0uHKN5SZNc",
        // var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNzE2ODUwOTkiLCJiYXRjaCI6Ii0xIiwiZXhwIjoxNTYzNTkxOTU5fQ.u-TABQZYHfMKgsQXC7GiR4BQB5fF_ozG6XlmAKiXLbU",
        userid = "73632852";

    if (bridge.call("account.getToken", null)) {
        token = bridge.call("account.getToken", null);
    }
    if (bridge.call("account.getUid", null)) {
        userid = bridge.call("account.getUid", null);
    }

    if (token) {
        localStorage.setItem("token", token);
    }
    if (userid) {
        localStorage.setItem("userid", userid);
    }

    var roomId = getQueryString("roomId");
    var requests = {
        // 分享接口：
        shareUrl: "http://47.112.149.8:8086/room/share?roomId=" + roomId,
        // 家族管理列表：
        searchFamily: "http://47.112.149.8:8084/family/searchFamily",
        // 获取房间榜单接口：
        getRoomRankingList: "http://47.112.149.8:8082/giftOrder/getRoomRankingList",
        // 申请进家族：
        joinFamily: "http://47.112.149.8:8084/family/joinFamily",

        // 未成年认证：
        nonageIdentification: "http://47.112.149.8:8084/nonageIdentification",
        // 提现记录：
        getSubmitRecord: "http://47.112.149.8:8084/getSubmitRecord",
        // 获取验证码
        smscode: "http://47.112.149.8:8084/account/smscode",
        // 绑定手机号
        bindingMobile: "http://47.112.149.8:8084/bindingMobile",
        // 用户可提现余额
        getBalance: "http://47.112.149.8:8084/getBalance",
        // 判断提现跳转路由：
        isBinding: "http://47.112.149.8:8084/isBinding",
        // 实名认证：
        identityVerify: "http://47.112.149.8:8084/identityVerify",
        // 绑定银行卡：
        bindingBankCard: "http://47.112.149.8:8084/bindingBankCard",
        //银行卡
        getBank: "http://47.112.149.8:8084/getBank",
        // 退出家族：
        outFamily: "http://47.112.149.8:8084/family/outFamily",
        // 收益记录、收益详情接口：
        getEarningsRecord: "http://47.112.149.8:8084/getEarningsRecord",
        // 提现接口：
        withdraw: "http://47.112.149.8:8084/withdraw",
        // 获取绑定的手机号接口
        getMobile: "http://47.112.149.8:8084/getMobile",
        // 提现页面，验证手机号码
        isMobileCode: "http://47.112.149.8:8084/isMobileCode",
        // 抽奖接口：http://127.0.0.1:8086/lottery/random?roomId=71097392
        lotteryRandom: "http://47.112.149.8:8086/lottery/random",
        //奖品列表： 
        lotteryPrizesAll: "http://47.112.149.8:8086/lottery/prizesAll",
        // 中奖记录：http://47.112.149.8:8086/lottery/list?roomId=71097392&limit=11
        lotteryList: "http://47.112.149.8:8086/lottery/list",
        // 我的中奖记录：
        getMyPrizes: "http://47.112.149.8:8086/lottery/getMyPrizes",
        token: localStorage.getItem("token"),
        keyword: getQueryString("family_id"),
        roomId: roomId,
        family_id: getQueryString("family_id"),
        userid: localStorage.getItem("userid")
    };
    return requests;
}

function lfAjax(config, callbackS, callbackF) {
    var url = config.url || '/';
    var method = config.method || 'GET';
    var async = config.async === undefined ? true : config.async;
    var contentType = config.contentType || 'application/x-www-form-urlencoded';
    var header = config.header || {};
    var data = config.data;
    // 创建XMLHttpRequest对象
    var xhr = new XMLHttpRequest();
    // 初始化请求
    xhr.open(method, url, async);
    // 设置header的默认值
    // xhr.setRequestHeader('Content-Type', value);
    // 设置其它header
    for (var item in header) {
        console.log(item, header[item]);
        xhr.setRequestHeader(item, header[item]);
        // 发送请求

        xhr.send(data);
        // 处理响应
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    callbackS && callbackS(xhr.responseText);
                } else { callbackF && callbackF(xhr.status); }
            }
        }
    }
}
//银行卡号校验
//Description: 银行卡号Luhm校验
//Luhm校验规则：16位银行卡号（19位通用）:
// 1.将未带校验位的 15（或18）位卡号从右依次编号 1 到 15（18），位于奇数位号上的数字乘以 2。
// 2.将奇位乘积的个十位全部相加，再加上所有偶数位上的数字。
// 3.将加法和加上校验位能被 10 整除。
function luhmCheck(bankno) {

    var num = /^\d*$/; //全数字
    if (!num.exec(bankno)) {
        //$("#banknoInfo").html("银行卡号必须全为数字");
        return false;
    }
    //开头6位
    var strBin = "10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99";
    if (strBin.indexOf(bankno.substring(0, 2)) == -1) {
        //$("#banknoInfo").html("银行卡号开头6位不符合规范");
        return false;
    }
    var lastNum = bankno.substr(bankno.length - 1, 1); //取出最后一位（与luhm进行比较）
    var first15Num = bankno.substr(0, bankno.length - 1); //前15或18位
    var newArr = new Array();
    for (var i = first15Num.length - 1; i > -1; i--) { //前15或18位倒序存进数组
        newArr.push(first15Num.substr(i, 1));
    }
    var arrJiShu = new Array(); //奇数位*2的积 <9
    var arrJiShu2 = new Array(); //奇数位*2的积 >9
    var arrOuShu = new Array(); //偶数位数组
    for (var j = 0; j < newArr.length; j++) {
        if ((j + 1) % 2 == 1) { //奇数位
            if (parseInt(newArr[j]) * 2 < 9) {
                arrJiShu.push(parseInt(newArr[j]) * 2);
            } else {
                arrJiShu2.push(parseInt(newArr[j]) * 2);
            }
        } else { //偶数位
            arrOuShu.push(newArr[j]);
        }
    }
    var jishu_child1 = new Array(); //奇数位*2 >9 的分割之后的数组个位数
    var jishu_child2 = new Array(); //奇数位*2 >9 的分割之后的数组十位数
    for (var h = 0; h < arrJiShu2.length; h++) {
        jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
        jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
    }
    var sumJiShu = 0; //奇数位*2 < 9 的数组之和
    var sumOuShu = 0; //偶数位数组之和
    var sumJiShuChild1 = 0; //奇数位*2 >9 的分割之后的数组个位数之和
    var sumJiShuChild2 = 0; //奇数位*2 >9 的分割之后的数组十位数之和
    var sumTotal = 0;
    for (var m = 0; m < arrJiShu.length; m++) {
        sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
    }
    for (var n = 0; n < arrOuShu.length; n++) {
        sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
    }
    for (var p = 0; p < jishu_child1.length; p++) {
        sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
        sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
    }
    //计算总和
    sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
    //计算Luhm值
    var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
    var luhm = 10 - k;
    if (lastNum == luhm) {
        //$("#banknoInfo").html("Luhm验证通过");
        return true;
    } else {
        //$("#banknoInfo").html("银行卡号必须符合Luhm校验");
        return false;
    }
    if (bankno.length < 15 && bankno.length > 20) {
        //$("#banknoInfo").html("银行卡号长度必须在16到19之间");
        return false;
    }
}

// 异步加载js文件的方法
var getScript = (function() {
    var cache = {}; //内部缓存下url,下次则不请求
    return function(url, fn) {
        if ("string" === typeof(url)) {
            url = [url]; //如果不是数组带个套
        };
        var i = 0, //循环起
            ok = 0, //加载成功几个js
            len = url.length, //一共几个js
            head = document.getElementsByTagName("head")[0],
            js, _url,
            create = function(url) { //创建js
                js = document.createElement("script");
                js.type = "text/javascript";
                js.src = url;
                head.appendChild(js);
                return js;
            };
        for (; i < len;) {
            if (cache[encodeURIComponent((_url = url[i++]))]) { //如果加载过
                (++ok >= len && fn) && fn(); //如果加载完所有的js则执行回调
                continue;
            }
            cache[encodeURIComponent(_url)] = !0; //设置缓存
            js = create(_url); //创建js
            fn && (js.onload = function() {
                if (++ok >= len) { //如果加载完所有的js则执行回调
                    fn();
                }
            });
        };
        head = js = _url = create = null;
        return this;
    }
})();

function uniqueArr(arr) {
    var hash = [];
    for (var i = 0; i < arr.length; i++) {
        if (hash.indexOf(arr[i]) == -1) {
            hash.push(arr[i]);
        }
    }
    return hash;
}
// 隐藏loading：
function hideLoadingDialog(msg) {
    bridge.call("app.hideLoadingDialog", msg);
}
// 显示loading
function showLoadingDialog(msg) {
    bridge.call("app.showLoadingDialog", msg);
}
// 关闭web页面
function finishPage(msg) {
    bridge.call("app.finishPage", msg);
}

/*bridge.call("app.showMsg",img); 显示toast信息*/
function showMsg(msg) {
    bridge.call("app.showMsg", msg);
}
// 显示用户主页
function userHomepage(uid) {
    bridge.call("app.userHomepage", JSON.stringify({ "uid": uid }));
}

function closeYeMian() {
    // 重置window.opener用来获取打开当前窗口的窗口引用
    　　 // 这里置为null,避免IE下弹出关闭页面确认框
    window.opener = null;
    // JS重写当前页面
    window.open("", "_self", "");
    // 顺理成章的关闭当前被重写的窗口
    window.close();
}

// 给电话号码加空格：
$("#mobile").keyup(function() {
    var len = $("#mobile").val().length;
    var reg = new RegExp("\\s", "g");
    var mobile_ = "";
    var mobile = $("#mobile").val();

    //  去掉空格
    mobile = mobile.replace(reg, "");
    for (var i = 0; i < len; i++) {
        if (i == 2 || i == 6) {
            mobile_ = mobile_ + mobile.charAt(i) + " ";
        } else {
            mobile_ = mobile_ + mobile.charAt(i);
        }
    }
    $("#mobile").attr("value", mobile_);
});

// onkeydown="isOnkeydown()" 时时监听 当是11位手机号时的回调：
function isOnkeydown(e) {
    var reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    var mobile = $("#mobile").val();
    if (!!(reg.test(mobile))) {
        return true
    }

}

// 判断手机号是否是正确的 
function isPhoneTel(str) {
    var reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
    if (reg.test(str)) {
        return true;
    } else {
        return false;
    }
}

// 验证身份证号码是否正确
function getShengFengZheng(str) {
    var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
    if (reg.test(str)) {
        return true;
    } else {
        return false;
    }
}

// 获取URL上的参数：

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

// 格式化时间：
function formatTime(time, cFormat) {
    if (arguments.length === 0) return null
    if ((time + '').length === 10) {
        time = +time * 1000
    }

    var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}',
        date
    if (typeof time === 'object') {
        date = time
    } else {
        date = new Date(time)
    }

    var formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    var time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        var value = formatObj[key]
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

// 切割数组
function chunk(arr, size) {
    var rsArr = [];
    for (var i = 0; i < arr.length; i += size) {
        var tempArr = [];
        for (var j = 0; j < size && i + j < arr.length; j++) {
            tempArr.push(arr[i + j]);
        }
        rsArr.push(tempArr);
    }
    return rsArr;
}